<template>
    <div class="body">
        <div class="userInfo">      
            <p>亲爱的:<strong>{{ state.user_info.username }}</strong></p>
        </div>
        <el-divider />
        <div class="bank_point">   
            <p>库币余额：<el-text size="large" type="danger">{{ state.user_info.bank_point }}</el-text></p>
            <el-button type="warning" @click="withdrawClick">提现</el-button>
            <el-popover
                placement="top-start"
                title="注意"
                :width="400"
                trigger="hover"
                content="提现库币必须是100的倍数，先提交申请单，审核通过后，管理员会联系你"
            >
                <template #reference>
                <el-button class="m-2">
                    <el-icon style="vertical-align: middle">
                    <QuestionFilled />
                    </el-icon>
                </el-button>
                </template>
            </el-popover>
            <div v-if="state.withdrawOrder !==''">
                <div class="withdrawOrder_now">
                    <p><el-text>交易类型：</el-text><el-text>提现</el-text></p>
                    <p><el-text>订单号：</el-text><el-text type="success">{{ state.withdrawOrder.order_id }}</el-text></p>
                    <p><el-text>交易日期：</el-text><el-text type="primary">{{ state.withdrawOrder.add_date }}</el-text></p>
                    <p><el-text>金额：</el-text><el-text type="warning">{{ state.withdrawOrder.amount }}</el-text></p>
                    <p><el-text>状态：</el-text><el-text type="danger">{{ state.withdrawOrder.status_cn }}</el-text></p>               
                </div>
                <div v-if="state.withdrawOrder.status==1">
                    <p>注：<strong>请您尽快联系管理员，告知订单号和收款微信号，既可收到转账！</strong></p>
                </div>
                
            </div>
            
            <el-divider />
            <div class="viewwithdrawOrderHistory">
                <span><strong>提现历史记录</strong></span>                
                <div>
                    <el-table ref="multipleTableRef" class="tableClass" :data="state.withdrawLogHistoryList" stripe
                        max-height="500"
                        :row-style="{height:50+'px'}" 
                        :cell-style="{padding:0+'px'}"
                        :header-cell-style="{ background: '#eef1f6', color: '#606266' }"
                        
                        border>                        
                        <el-table-column type="index" width="45" label="序" />
                        <el-table-column width="250" property="order_id" label="单号" show-overflow-tooltip />
                        <el-table-column width="100" property="amount" label="库币" show-overflow-tooltip />
                        <el-table-column width="200" property="add_date" label="日期" show-overflow-tooltip />
                        <el-table-column width="200" property="status_cn" label="状态" show-overflow-tooltip />                       
                    </el-table>
                    <el-pagination
                        background
                        layout="total, pre, pager, next"
                        :total="state.total"                
                        :page-size="state.pageSize"            
                        @current-change="handleCurrentChange"
                    />
                </div>
            </div>
        </div>
        <div class="dialog">        
            <el-dialog v-model="state.withdrawVisible" title="提现">
            <p><strong>注意：提交提现订单成功后，联系管理员，告知提现订单号，核对身份后，管理员转账给您</strong></p>
                <el-form :model="state.withdrawForm" :rules="state.rules" ref="withdrawFormRef">               
                    <el-form-item label="充值库币：" prop="amount">
                        <el-input-number :min="100" :max="900" v-model="state.withdrawForm.amount" :step="100" />
                    </el-form-item>
                </el-form>
                        
                <template #footer>
                <span class="dialog-footer">
                    <el-button @click="state.withdrawVisible = false">取消</el-button>
                    <el-button type="warning" @click="submmitWithdrawClick">
                        确认
                    </el-button>
                </span>
                </template>
            </el-dialog>
        </div>
    </div>
</template>
  
<script setup>
import axios from '@/utils/axios'
import { reactive, ref } from 'vue'
import { localGet, verifyToken } from '@/utils'
import { onMounted } from "@vue/runtime-core"
import { ElMessage } from 'element-plus'
import { QuestionFilled } from '@element-plus/icons-vue'

const withdrawFormRef=ref(null)
const isNum=(rule, amount, callback)=> {
    var reg=/^\d{3}$/;
    if(!reg.test(amount)){
        return false;
    }else
    if(amount % 100 != 0){
        return false;
    }else{
        return true;
    }
  }
const state = reactive({
    withdrawHistoryVisible:false,
    query_status: -1,
    withdrawLogHistoryList:[],
    orderUnique:'',
    user_info: Object,   
    withdrawOrder: '',  
    withdrawVisible:false,
    total: 49, // 总条数
   currentPage: 1, // 当前页
   pageSize: 10, // 分页大小
    withdrawForm:{
      amount:100,
    },  
    rules: { // 规则
      amount: [
        {required: 'true', message: '请填写金额', trigger: ['change']},
        {validator: isNum, message: '100至1000之间的100倍整数',trigger: 'blur' },     
      ]
    },
})
// 查询自己的提现记录
const getOwnerWithdrawLog = ()=>{
    let params = {
            query_key: state.query_status,
            page: state.currentPage,
            size: state.size,
        }
        axios.get(`/WithdrawLogModelViewSet/get_owner_withdraw_log/`, {params}).then((res) => {
            console.log("查询自己的提现历史记录",res)
          if(res.code==200){ 
          state.withdrawLogHistoryList = res.data.results
          state.withdrawOrder = res.data.results[0]
          state.total = res.total
          }else{
            console.log("提交失败", res)
          }       
        }).catch((error)=>{
          console.log("错误：", error)
        })
}
onMounted(()=>{ 

    // 先更新用户的资料，防治旧的库币可以提现
    verifyToken()
    state.user_info=localGet("user_information")
    // console.log('用户信息：', localGet("user_information"))
    state.orderUnique=state.user_info.username + Date.parse(new Date()) + Math.ceil(Math.random()*10000)
    getOwnerWithdrawLog()
}) 

// 提现点击事件
const withdrawClick=()=>{
    state.withdrawVisible = true;
    console.log('用户要提现啦');
}
// 获取行数据
const getRowKeys=()=>{
    console.log('获取行数据')
}
// 提交提现事件
const submmitWithdrawClick=()=>{
    console.log("当前申请提现金额：", state.withdrawForm.amount)
    console.log("账号库币余额", state.user_info.bank_point)
    if(state.withdrawForm.amount > state.user_info.bank_point){
        ElMessage.warning("余额不够！")
        return false
    }
    withdrawFormRef.value.validate((vaild, obj) => {
      if (vaild) {
        let params = {
            orderUnique: state.orderUnique,          
            amount: state.withdrawForm.amount,
        }
        axios.post(`/WithdrawLogModelViewSet/create_withdraw_log/`, params).then((res) => {
          if(res.code==200){
          ElMessage.success( '提现申请成功！')
          state.withdrawOrder = res.data.results
          state.withdrawVisible = false;
          getOwnerWithdrawLog()
          }else
          if(res.code==1022){
            ElMessage.warning( '最近存在未支付的提现，先联系管理员处理后，再提交提现申请！')
          }
          else{
            console.log("提交失败", res)
          }       
        }).catch((error)=>{
          console.log("错误：", error)
        })
      }else{                //输出表单没有通过的原因
        console.log("表单没有通过！",obj)
        for (let key in obj) {
          console.log(obj[key][0].message)
          return false;
        }   
      }
    })

}

//点击页码时触发
const handleCurrentChange = (newPage)=>{
   state.currentPage = newPage 
   getOwnerWithdrawLog()
 }
</script>

<style scoped>
    .body{
        margin: 8px;
    }
    .userInfo{
        padding: 8px;
    }
    .withdrawOrder_now{
        margin: 8px;
        padding: 5px;
        border-style: solid;
        border-width: 1px;
        border-radius: 10px;
    }
</style>